package server.tasks;

import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;

import server.ClientInfo;
import server.Logger;
import server.ProxyCore;

public class ClientReceiverTask implements Runnable {
	private ServerSocket serverSocket;
	private ProxyCore proxy;
	private boolean stop = false;
	
	public ClientReceiverTask(ServerSocket serverSocket, ProxyCore proxy) {
		this.serverSocket = serverSocket;
		this.proxy = proxy;
	}

	@Override
    public void run() {
        while (stop == false) {
    		Socket socket;
			try {
				Logger.logEvent("Gotowosc na przyjecie kolejnego klienta..", Logger.LOG_INFO);
				socket = serverSocket.accept();		
				String IP = socket.getInetAddress().getHostAddress();
				Logger.logEvent("Nowy klient polaczony z adresu IP: " +  socket.getInetAddress().getHostAddress(), 
								Logger.LOG_INFO);
	    		
				ClientInfo client = new ClientInfo();
	    		client.AssignedSocket = socket;
	    		client.setIP(IP);
	    		ClientTask task = new ClientTask(client, proxy);	    		
	    		client.setTask(task);	    		
	    		proxy.addClient(client);
	    		proxy.exec.execute(task);
			} catch (IOException e) {
				//server socket zamkniety - zakoncz watek
				return;
			}
        }   	
    }	
	
	public void stop() {
		stop = true;
	}
}
